﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SoftwareMonkeys.LogClimber.Entities;
using System.Xml;
using System.Xml.Serialization;

namespace SoftwareMonkeys.LogClimber.Business
{
	public class LogTreeLoader
	{
		public Log[] LoadLogs(string wwwDirectory)
		{
			if (wwwDirectory == null || wwwDirectory == String.Empty)
				throw new ArgumentNullException(wwwDirectory);

			// Use the trees directory
			string logsDirectory = wwwDirectory + Path.DirectorySeparatorChar + "App_Data" + Path.DirectorySeparatorChar + "Logs";

			//PrepareLogs(logsDirectory);

			return LoadLogsFromLogsDirectory(logsDirectory);

		}
		
		public Log LoadLog(string logFilePath)
		{
			if (logFilePath == null || logFilePath == String.Empty)
				throw new ArgumentNullException(logFilePath);

			if (!File.Exists(logFilePath))
				throw new Exception("Can't find log file: " + logFilePath);

			string dateStamp = Path.GetFileName(Path.GetDirectoryName(logFilePath));
			
			LogGrower grower = new LogGrower(Path.GetDirectoryName(logFilePath));

			Log log = grower.GrowTreeFromFile(logFilePath);

			log.DateStamp = dateStamp;

			return log;

		}

		/// <summary>
		/// Loads all the logs from the specified directory as trees.
		/// </summary>
		/// <param name="logsDirectory"></param>
		/// <returns></returns>
		private Log[] LoadLogsFromLogsDirectory(string logsDirectory)
		{
			List<Log> logs = new List<Log>();
			
			foreach (string dateDirectory in Directory.GetDirectories(logsDirectory))
			{
				string filePath = dateDirectory + Path.DirectorySeparatorChar +
					"Log.xml";

				logs.Add(LoadLog(filePath));
			}

			return logs.ToArray();
		}

		// TODO: Clean up if not needed
		/*private Log LoadLogFromIndex(string indexFilePath)
        {
            if (!File.Exists(indexFilePath))
                throw new ArgumentException("Can't find the index file. The logs must not have been created, or have been corrupted.","indexFilePath");
            else
            {

                List<Log> list = new List<Log>();

                XmlDocument document = new XmlDocument();
                document.Load(indexFilePath);

                string treesDirectoryPath = Path.GetDirectoryName(indexFilePath);

                foreach (XmlNode node in document.DocumentElement.ChildNodes)
                {
                    Guid treeID = new Guid(node.Attributes["ID"].Value);

                    string treePath = treesDirectoryPath + Path.DirectorySeparatorChar
                        + treeID.ToString() + ".xml";

                    list.Add(LoadLogFromFile(treePath));

                }

                Log[] logs = list.ToArray();

                Log log = CompileTreeThreads(logs);

                return log;
            }
        }*/

		/*private Log CompileTreeThreads(Log[] threads)
        {
            Log log = new Log();

            foreach (Log thread in threads)
            {
                if (thread.ChildEntries != null)
                {
                    foreach (Entry entry in thread.ChildEntries)
                    {
                        log.AppendChild(entry);
                    }
                }
            }

            return log;
        }*/

		/* private XmlDocument LoadLogFromFile(string filePath)
        {
            Log log = null;

            using (StreamReader reader = new StreamReader(File.OpenRead(filePath)))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Log));
                log = (Log)serializer.Deserialize(reader);
            }

            return log;
        }*/

		/*private void PrepareLogs(string logsDirectory)
        {
            foreach (string directory in Directory.GetDirectories(logsDirectory))
            {
                string logFile = directory + Path.DirectorySeparatorChar + "Log.xml";

                if (File.Exists(logFile))
                {


                    // TODO: Remove if not needed. Should be obsolete.
                    LogThreader threader = new LogThreader(logsDirectory, Path.GetFileName(directory));

                    threader.SplitThreads();

                    LogGrower grower = new LogGrower(directory);

                    grower.CreateTrees();
                }
                else
                {
                    // Ignore
                }
            }
        }*/
	}
}
